<template>
  <div class="app-container">
    <!-- 用户信息展示 -->
    <!-- 搜索功能 -->
    <div>
      <el-input v-model="search" class="input" placeholder="请输入搜索内容" @keyup.enter.native="get_search" :clearable="true"></el-input>
      <el-button type="primary" @click="get_search">搜索</el-button>
    </div>
    <!-- 开关 -->

    <el-switch style="display: block" v-model="user_switch" active-color="#1366ce" inactive-color="#ff4949" active-text="账户信息" inactive-text='基本信息' align='right'>
    </el-switch>
    <br>
    <el-table ref="multipleTable" v-loading="listLoading" :data="userlist" element-loading-text="Loading" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column align="center" type='index' label="序号" width="55">
      </el-table-column>
      <el-table-column label="头像" width='70px' align="center">
        <template slot-scope="scope">
          <el-row class="demo-avatar demo-basic">
            <el-col :span="12">
              <div class="demo-basic--circle">
                <div class="block">
                  <el-avatar :size="50" :src="get_photo(scope.row.photo)"></el-avatar>
                </div>
              </div>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop='username'>
      </el-table-column>
      <el-table-column label="用户ID" width='70px' align="center" prop='id'>
      </el-table-column>
      <el-table-column label="邮箱" v-if="user_switch" align="center" prop='email'>
      </el-table-column>
      <el-table-column label="手机" v-if="user_switch" align="center" prop='phone'>
      </el-table-column>
      <el-table-column label="职业" width='70px' v-if="user_switch" align="center" prop='occupation'>
      </el-table-column>
      <el-table-column label="学校/公司" v-if="user_switch" align="center" prop='school'>
      </el-table-column>
      <el-table-column label="经验值" v-if="user_switch" align="center" prop='experience'>
      </el-table-column>
      <el-table-column label="会员等级" v-if="!user_switch" align="center" prop='vid'>
      </el-table-column>
      <el-table-column label="会员期至" v-if="!user_switch" align="center" prop='vip_time'>
      </el-table-column>
      <el-table-column label="余额" v-if="!user_switch" align="center" prop='balance'>
      </el-table-column>
      <el-table-column label="实验豆" v-if="!user_switch" align="center" prop='bean'>
      </el-table-column>
      <el-table-column label="邀请码" v-if="!user_switch" align="center" prop='code'>
      </el-table-column>
      <el-table-column label="操作" width='200px' align="center" prop=''>
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="注册日期" width='200px'>
        <template slot-scope="scope">
          <i class="el-icon-time" />{{ scope.row.date_joined|date_time }}
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-button type="primary" round @click='del_multi'>批量删除</el-button>

    <el-button @click="toggleSelection()" round>取消选择</el-button>
    <br>
    <el-pagination background :hide-on-single-page='true' layout="prev, pager, next" align='center' :total="total" @current-change='change_page'>
    </el-pagination>
    <!-- 修改用户 -->
    <el-dialog title="修改用户" :visible.sync="UpdateUser" top="5vh">
      <el-form :model="user" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="user.username" type="text" size="30" :maxlength="18" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="密码">
          <el-input v-model="user.password" type="password" show-password size="30" :maxlength="18"></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="user.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" :maxlength="11">
          <el-input v-model="user.phone"></el-input>
        </el-form-item>

        <el-form-item label="职业">
          <el-input v-model="user.occupation"></el-input>
        </el-form-item>

        <el-form-item label="学校/公司">
          <el-input v-model="user.school"></el-input>
        </el-form-item>

        <el-form-item label="会员等级">
          <el-select v-model="user.vid" clearable>
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="user.balance"></el-input>
        </el-form-item>

        <el-form-item label="实验豆">
          <el-input v-model="user.bean"></el-input>
        </el-form-item>

        <el-form-item label="经验值">
          <el-input v-model="user.experience"></el-input>
        </el-form-item>

        <el-form-item label="邀请码" :maxlength="8">
          <el-input v-model="user.code"></el-input>
        </el-form-item>
        <el-form-item label="个人简介" :maxlength="8">
          <el-input type="textarea" v-model="user.sign"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消修改</el-button>
        <el-button type="primary" @click="submit">提交修改</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { get_user_get, user_delete, user_put } from "../axios_api/api"
import { getList } from '@/api/table'
import { constants } from 'zlib';

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      options: [{ value: "普通用户", label: "普通用户" }, { value: "普通会员", label: "普通会员" }, { value: "高级会员", label: "高级会员" }],
      user: {
				username: "",
				password: "",
        email: "",
        phone: "",
        occupation: "",
        school: "",
        vid: "",
        balance: "",
        bean: "",
        experience: "",
        code: "",
        sign: "",
      },
      search: "",
      update: false,
      list: null,
      listLoading: true,
      user_switch: true,
      // 用户列表变量
      userlist: [],
      // vip变量
      vipdatas: {},
      // 管理员名
      username: localStorage.getItem("username"),
      // 弹窗变量
      UpdateUser: false,
      AddUser: false,
      DeleteUser: false,
      datas: {},
      // 分页
      total: 0,
      page: 1,
      size: 10,
      multipleSelection: [],
    }
  },
  mounted() {
    this.get_user();
  },
  methods: {
    // 搜索
    get_search() {
      this.get_user();
    },
    // 提交修改
    submit() {
      // 正则判断用户名是否规范
      if (!/^[a-zA-Z]([a-zA-Z0-9]){5,16}$/.test(this.user.username)) {
        this.$message.error("用户名以字母开头，且不小于6位")
        return false
      }
      // 正则判断密码是否规范
      if (!/^[a-zA-Z]([a-zA-Z0-9]){5,16}$/.test(this.user.password)) {
        this.$message.error("密码以字母开头，且不小于6位")
        return false
      }
      // 正则判断邮箱是否规范
      if (!/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(this.user.email)) {
        this.$message.error("邮箱格式不正确")
        return false
      }
      // 正则判断手机号是否规范
      if (!/^(13[0-9]{9})|(15[0-9][0-9]{8})|(18[0-9][0-9]{8})$/.test(this.user.phone)) {
        this.$message.error("手机号格式不正确")
        return false
      }
      for (let i = 0; i < this.vipdatas.length; i++) {
        if (this.user.vid === this.vipdatas[i].grade) {
          this.user.vid = this.vipdatas[i].id
        }
      }
      let data = this.user
      this.$confirm('此操作将直接修改此用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        user_put(data).then(resp => {
          if (resp.code === 200) {
            this.$message.success("修改成功")
            this.get_user()
            this.UpdateUser = false
          }
        })
      }).catch(() => {
        this.get_user()
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
        this.UpdateUser = false;
      });
    },
    // 取消修改
    cancel() {
      this.get_user()
      this.$message({
        type: 'info',
        message: '已取消修改'
      });
      this.UpdateUser = false;
    },
    // 动态拼接头像
    get_photo(img) {
      if (img == '1.jpg') {
        return require('../../../static/img/1.jpg')
      } else {
        // return img 返回七牛云图片链接
        return 'http://q9j3oo8by.bkt.clouddn.com/' + img
      }
    },
    // 换页
    change_page(val) {
      this.page = val
      this.get_user()
    },
    // 获取多选值
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 编辑
    handleEdit(index, data) {
      this.UpdateUser = true;
      this.user = data

    },
    // 删除
    handleDelete(index, data) {
      this.submit_loading = true
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = { uid: String(data.id) }
        user_delete(params).then(resp => {
          this.$message.success(resp.message)
          this.get_user()
          this.submit_loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量删除
    del_multi() {
      console.log(this.multipleSelection)
      this.submit_loading = true
      let id = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        id.push(this.multipleSelection[i].id)
      }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = { id_list: String(id) }
        user_delete(params).then(resp => {
          this.$message.success("批量删除成功")
          this.get_user()
          this.submit_loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    // 取消选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 获取用户列表
    get_user() {
      this.listLoading = true
      get_user_get({ "page": this.page, "size": this.size, "search": this.search }).then(resp => {
        if (resp.code === 200) {
          this.total = resp.count
          // 将用户传入userlist列表中
          this.userlist = resp.userlist;
          this.vipdatas = resp.viplist;
          console.log(this.userlist)
          this.listLoading = false

          // 将用户vid字段赋值为会员grade字段
          for (let i = 0; i < resp.userlist.length; i++) {
            for (let j = 0; j < resp.viplist.length; j++) {
              if (this.userlist[i].vid === resp.viplist[j].id)
                this.userlist[i].vid = resp.viplist[j].grade
            }
          }
        }
      })
    },
  },
  filters: {
    date_time(value) {
      return value.split('T').join(' ').split('.')[0]
    }
  }
}
</script>
<style>
.input {
  width: 800px;
  float: left;
  margin: 0 10px 0 400px;
  margin-right: 5px;
}
</style>